<template>
  <div style="border: 1px solid #ccc;" v-loading="loading">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden;"
      v-model="value"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
      @onChange="onChange"
    />
  </div>
</template>
<script>
import Vue from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import baseUrl from "@/api/request/url";
import { developmentUrl, isDev } from "@/configurations";
import { Boot } from "@wangeditor/editor";
import attachmentModule from "@wangeditor/plugin-upload-attachment";
// 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册
Boot.registerModule(attachmentModule);
import axios from "axios";
export default Vue.extend({
  components: { Editor, Toolbar },
  props: {
    value: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 自定义插入图片/视频
    const handleUpload = async (file, insertFn) => {
      let form = new FormData();
      form.append("files", file);
      let url = isDev ? developmentUrl : baseUrl;
      let { data } = await uploadFile(form); //获取服务器文件返回列表
      insertFn(`${url}${data[0]}`, `${file.name}`, `${url}${data[0]}`);
      this.loading = false;
      // 最后插入图片 insertFn方法参数(url, alt, href)，路径根据自己的项目需求配置
    };
    // 自定义插入附件
    const fujianHandleUpload = async (file, insertFn) => {
      let form = new FormData();
      form.append("files", file);
      let url = isDev ? developmentUrl : baseUrl;
      let { data } = await uploadFile(form); //获取服务器文件返回列表
      insertFn(`${url}${data[0]}`, `${url}${data[0]}`, `${url}${data[0]}`);
      this.loading = false;
      // 最后插入图片 insertFn方法参数(url, alt, href)，路径根据自己的项目需求配置
    };
    //上传图片/视频方法
    const uploadFile = async form => {
      let data = form;
      if (!form instanceof FormData) {
        data = JSON.stringify(params);
      }
      this.loading = true;
      let res = await axios({
        method: "POST",
        url: `${baseUrl}${`/uploadFile/uploadFile`}`,
        data
      });
      return res.data;
    };

    //上传的配置
    const editorConfig = {
      placeholder: "请输入内容...",
      hoverbarKeys: {
        attachment: {
          menuKeys: ["downloadAttachment"] // “下载附件”菜单
        }
      },
      MENU_CONF: {
        uploadImage: {
          //上传图片配置
          customUpload: handleUpload
        },
        uploadVideo: {
          //上传视频配置
          customUpload: handleUpload
        },
        // 上传附件
        uploadAttachment: {
          title: "上传附件",
          fieldName: "file",
          // 超时时间，默认为 10 秒
          timeout: 100 * 1000, // 5 秒
          customUpload: fujianHandleUpload // 上传方法
        }
      }
    };
    return {
      editor: null,
      toolbarConfig: {
        insertKeys: {
          index: 22, // 自定义插件在工具栏显示的位置
          keys: ["uploadAttachment"] // 查看名称
        }
      },
      loading: false,
      content: "",
      editorConfig: editorConfig,
      mode: "default",
      content: ""
    };
  },
  mounted() {},
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    onChange(editor) {
      this.$emit("input", editor.getHtml());
    },
    onDestroyed(editor) {
      console.log("onDestroyed", editor);
    },
    onMaxLength(editor) {
      console.log("onMaxLength", editor);
    },
    onFocus(editor) {
      console.log("onFocus", editor);
    },
    onBlur(editor) {
      console.log("onBlur", editor);
    },
    customAlert(info, type) {
      window.alert(`customAlert in Vue demo\n${type}:\n${info}`);
    },
    customPaste(editor, event, callback) {
      //   console.log("ClipboardEvent 粘贴事件对象", event);
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）
      // 返回 false ，阻止默认粘贴行为
      event.preventDefault();
      callback(false); // 返回值（注意，vue 事件的返回值，不能用 return）
    }
  },

  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  }
});
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.w-e-text {
  margin: 0 10px !important;
}
</style>
